package com.yuandengta.yomall.product.service.impl;

import com.yuandengta.common.to.SkuReductionTO;
import com.yuandengta.yomall.product.entity.*;
import com.yuandengta.yomall.product.feign.CouponFeignService;
import com.yuandengta.yomall.product.service.*;
import com.yuandengta.yomall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.product.dao.SkuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import com.yuandengta.common.utils.R;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu对应的sku
     *
     * @param spuInfoEntity
     * @param skus
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSkuInfo(SpuInfoEntity spuInfoEntity, List<Skus> skus) {
        skus.forEach(sku -> {
            // 保存sku基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSaleCount(0L);
            String defaultImage = "";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImage = image.getImgUrl();
                }
            }
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            this.save(skuInfoEntity);

            // 批量保存sku图片
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setDefaultImg(image.getDefaultImg());
                skuImagesEntity.setImgUrl(image.getImgUrl());
                return skuImagesEntity;
            }).filter(skuImagesEntity -> {
                return !StringUtils.isEmpty(skuImagesEntity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            // 批量保存sku属性值
            List<SkuSaleAttrValueEntity> collect = sku.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(collect);

            // 保存优惠，满减等信息
            SkuReductionTO skuReductionTO = new SkuReductionTO();
            BeanUtils.copyProperties(sku, skuReductionTO);
            skuReductionTO.setSkuId(skuId);
            if (skuReductionTO.getFullCount() > 0
                    || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                R r = couponFeignService.savaReduction(skuReductionTO);
                if (r.getCode() != 0) {
                    // TODO 数据一致性问题：分布式事务
                    log.error("调用远程服务 yomall-coupon 保存SKU优惠信息失败");
                }
            }
        });
    }

    /**
     * SKU 检索
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && !"0".equalsIgnoreCase(max)) {
            queryWrapper.le("price", max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Override
    public SkuItemVO item(Long skuId) {
        SkuItemVO skuItemVO = new SkuItemVO();
//1.sku基本信息 pms_sku_info
        SkuInfoEntity skuInfo = getById(skuId);
        skuItemVO.setSkuInfo(skuInfo);
        Long spuId = skuInfo.getSpuId();
        Long catalogId = skuInfo.getCatalogId();
// TODO 查询库存
        skuItemVO.setHasStock(true);
// 2.sku图片信息 pms_sku_images
        List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
        skuItemVO.setImages(images);
//3.spu销售属性组合
        List<SkuSaleAttrVO> saleAttrs =
                skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
        skuItemVO.setSaleAttrs(saleAttrs);

// 4.spu商品介绍
        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
        skuItemVO.setSpuDesc(spuInfoDescEntity);
// 5.spu规格参数
        List<SpuAttrGroupVO> groupAttrs =
                attrGroupService.getAttrGroupWithAttrsBySpuId(catalogId, spuId);

        skuItemVO.setGroupAttrs(groupAttrs);

        return skuItemVO;
    }

}
